# Generated by Django 2.2.12 on 2020-05-14 13:59

import django.db.models.deletion
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import migrations, models
from rolepermissions.roles import assign_role


def migrate_organization(apps, schema_editor):
    Organization = apps.get_model("orga", "Organization")
    User = get_user_model()
    EmailAddress = apps.get_model("account", "EmailAddress")
    UserProfile = apps.get_model("user", "UserProfile")
    Address = apps.get_model("common", "Address")

    for orga in Organization.objects.all():
        coordinator_names = orga.coordinator_fullname.split(" ")
        if coordinator_names or orga.coordinator_email:
            user, create = User.objects.get_or_create(
                email=orga.coordinator_email,
                is_active=True,
                defaults={
                    "first_name": coordinator_names[0]
                    if len(coordinator_names) > 0
                    else "",
                    "last_name": " ".join(coordinator_names[1:])
                    if len(coordinator_names) > 1
                    else "",
                },
            )
            if create:
                user.set_unusable_password()
                address_ptr = Address.objects.create()
                UserProfile.objects.create(
                    user_id=user.id,
                    natel=orga.coordinator_natel,
                    phone=orga.coordinator_phone,
                    status=10,  # USERSTATUS_ACTIVE
                    address_ptr_id=address_ptr.id,
                )
                email_address, _ = EmailAddress.objects.get_or_create(
                    email=user.email, defaults={"user_id": user.id}
                )
                email_address.user_id = user.id
                email_address.verified = True
                email_address.primary = True
                email_address.save()

            user.is_active = True
            user.save()
            orga.coordinator_id = user.id
            orga.save()
            assign_role(user, "coordinator")


class Migration(migrations.Migration):
    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("orga", "0006_auto_20170831_1201"),
        ("user", "0059_userprofile_phone"),
    ]

    operations = [
        migrations.AddField(
            model_name="organization",
            name="coordinator",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="managed_organizations",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Coordina·teur·trice",
            ),
        ),
        migrations.RunPython(migrate_organization),
    ]
